package com.bto.solar.work.controller;

import com.bto.solar.work.common.BizException;
import com.bto.solar.work.common.R;
import com.bto.solar.work.dto.lease.ContractFileRes;
import com.bto.solar.work.service.BtoLeaseReviewService;
import com.bto.solar.work.utils.ServletUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author adrian
 * @since 2023-08-09
 */
@RestController
@RequestMapping("/leaseContract")
public class LeaseContractController {

    @Autowired
    private BtoLeaseReviewService btoLeaseReviewService;

    @GetMapping("/contract-type/file-url")
    public R<ContractFileRes.Contract.FileMessage> getContractTypeFileUrl(@RequestParam String orderId,
                                                                          @RequestParam String contractType) {
        return R.ok(btoLeaseReviewService.getContractFile(orderId, contractType));
    }

    @ApiModelProperty("输出越秀合同文本-测试使用")
    @GetMapping("/get-url")
    public void getPDf(@RequestParam String orderId,
                       @RequestParam String contractType)  {
        try {
            btoLeaseReviewService.getPDF(orderId, contractType, Objects.requireNonNull(ServletUtils.getResponse()));
        } catch (IOException e) {
            throw new BizException("订单号：{}，越秀合同类型为：{}，文件输出流错误: "+e.getMessage(), orderId, contractType);
        } catch (Exception e) {
            throw new BizException("订单号：{}，" + e.getMessage(), orderId);
        }

    }

    /**
    *  前端请求,拿到越秀合同url（流形式-下载模式），流转会前端
    */
    @GetMapping(value = "/get-pdf", produces = MediaType.APPLICATION_PDF_VALUE)
    public byte[] getPdf(@RequestParam String orderId,
                         @RequestParam String contractType)  {
        try {
            return btoLeaseReviewService.getPdfBytes(orderId, contractType);
        } catch (IOException e) {
            throw new BizException("订单号：{}，越秀合同类型为：{}，文件输出流错误: "+e.getMessage(), orderId, contractType);
        }
    }

    /**
     * 越秀合同下载按钮控制
     */
    @GetMapping("/has-get-sign-btn")
    public R<Map<String, Boolean>> getSignUrlByUseId() {
        return R.ok(btoLeaseReviewService.getSignUrlByUseId());
    }


}
